define(function(require){

    var orderTable;
    var firstTime = true;

    //include
    require('./list-tpl');


    var listTpl = juicer.templates['list.juicer.html'];



    window.getParamByUrl = function(key) {
        var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return r[2];
        return '';
    }

    var shopName = decodeURIComponent( getParamByUrl('shopName') ) ;

    var shopId = getParamByUrl('shopId');


    var orderId = decodeURIComponent( getParamByUrl('orderId') ) ;








    var List = {
        init : function() {
            shopName && $('h1').html(shopName+'订单查询');
            this.initOrderTable();
            this.iniQuerytValidator();
            this.initDatetimepicker();
            this.bindEvent();

        },
        /**
         * 表单验证初始化
         */
        iniQuerytValidator : function() {

            var fields = {}
            if(!shopId){

                fields = {serarch_value: {
                        validators: {
                            message: '电话输入错误',
                            phone: {
                                country: 'CN',
                                message: '请输入正确的电话格式'
                            },
                            callback: {
                                message: '请输入号码或者订单ID或者物流单号与时间',
                                callback: function(value, validator) {
                                    if(!value && !$("#search_bizOrderId").val() && !$("#outWayId").val() && !$("#search_logisticsNo").val()) {
                                        return false;
                                    }else{
                                        return true;
                                    }
                                }
                            }
                        }
                    }}
            }
            $('#query_form').bootstrapValidator({
                message: '输入错误',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: fields
            });
        },
        initDatetimepicker : function() {
            $('.form_date').datetimepicker({
                language:  'zh-CN',
                weekStart: 1,
                todayBtn:  1,
                autoclose: 1,
                todayHighlight: 1,
                startView: 2,
                minView: 2,
                forceParse: 0
            });
        },
        searchList : function(){
            var gmtCreateStart = + new Date($("#gmtCreateStart").val()),
                gmtCreateEnd = + new Date($("#gmtCreateEnd").val());

            if(gmtCreateEnd < gmtCreateStart) {
                CRM.showDialog('结束时间不能小于开始时间，请重新选择');
                return;
            }
            $("#query_form").data('bootstrapValidator').resetForm();
            $("#query_form").data('bootstrapValidator').validate();
            if ($("#query_form").data('bootstrapValidator').isValid()) {
                $('#order_table').DataTable().ajax.reload();
            }
        },
        /**
         * 初始化订单的列表
         */
        initOrderTable : function() {
            orderTable = $("#order_table").dataTable({
                "oLanguage": CRM.pageConfig,
                "sScrollX": "100%",   //表格的宽度
                "sScrollXInner": "100%",   //表格的内容宽度
                "bScrollCollapse": true,  //当显示的数据不足以支撑表格的默认的高度时，依然显示纵向的滚动条。(默认是false)
                "bPaginate": true,  //是否显示分页
                "bLengthChange": true,  //每页显示的记录数
                "bFilter": false, //搜索栏
                "bSort": false, //是否支持排序功能
                "bInfo": false, //显示表格信息
                "bAutoWidth": false,  //自适应宽度
                "bServerSide": true,//开启服务端处理
                "sAjaxSource": CRM.getOuterUrl('/trade/crm/order/queryOrderList'),
                "fnInitComplete": function () {
                    this.fnAdjustColumnSizing(true);
                },
                "fnServerData": function (sSource, aoData, fnCallback) {
                    if (firstTime) {
                        firstTime = false;
                        return;
                    }
                    var searchType = $("#search_type").val(),
                        searchVal = $("#serarch_value").val(),
                        searchVal = $.trim(searchVal);
                        searchJson = (searchType == 'mobile' ? {"mobile" : searchVal} : {"orderMobile" : searchVal});


                    var dataString = JSON.stringify($.extend({
                        bizOrderId:$("#search_bizOrderId").val(),
                        outWayId:$("#outWayId").val(),
                        logisticsNo:$("#search_logisticsNo").val(),
                        gmtCreateStart:$("#gmtCreateStart").val(),
                        gmtCreateEnd:$("#gmtCreateEnd").val(),
                        orderType : $("#orderType").val(),
                        "operator": $.cookie('_uk'),
                        "pageNum": aoData[3].value / aoData[4].value + 1,
                        "pageSize": aoData[4].value,
                        shopId:shopId

                    },  searchJson));

                    $.ajax({
                        "type": 'POST',
                        "url": sSource,
                        "dataType": "json",
                        contentType: "application/json",
                        xhrFields: {
                            withCredentials: true
                        },
                        "data": dataString,
                        contentType: "application/json",
                        "success": function (req) {

                            if(req.status == false && req.responseCode == 10212){
                                var loc = location.href;
                                location.href = CRM.getOuterUrl('/member/login.html?redirectUrl='+encodeURIComponent(loc));
                            }
                            else if (req.responseCode && req.status) {
                                var resultData = CRM.getDataTabelDtaObject();
                                if (req.entry) {
                                    resultData.iTotalDisplayRecords = 9999;
                                    resultData.iTotalRecords = 9999;
                                    for (var length in req.entry) {
                                        eval('req.entry[length].attributes=' + req.entry[length].attributes);
                                        if(!req.entry[length].attributes){
                                            req.entry[length].attributes = "";
                                        }
                                        resultData.aaData.push([req.entry[length]]);
                                    }
                                }
                            } else {
                                $("#msg_dialog_content").text(req.message);
                                $('#msg_dialog').modal('show');
                            }
                            fnCallback(resultData);
                        },
                        error: function (e) {
                            //请求出错处理
                            $("#msg_dialog_content").text("订单列表,请求服务异常！");
                            $('#msg_dialog').modal('show');
                        }
                    });
                },
                "aoColumns": [
                    {
                        "bSortable": false,
                        "mRender": function (data, type, row) {


                            return renderOrderListMain(data);
                        }
                    }

                ], //列设置，表有几列，数组就有几项
                "bStateSave": true, //保存状态到cookie *************** 很重要 ， 当搜索的时候页面一刷新会导致搜索的消失。使用这个属性就可避免了
                "sPaginationType": "simple" //分页，一共两种样式，full_numbers和two_button(默认)

            });
        },
        bindEvent : function() {
            var self = this;
            var elSearch = $("#search_btn")
            elSearch.on('click', function () {
                $('#order_table_wrap').show();
                $('#order_error_table_wrap').hide();
                self.searchList();
            });



            if(shopId || orderId){
                $('#search_bizOrderId').val(orderId);
                elSearch.trigger('click');
            }

            $("#search_type").on('change', function () {
                $("#serarch_value").attr("placeholder", $("#search_type").find("option:selected").text());
            });
            $(document).on('click', '.J_groupid', function (ev) {
                //ev.preventdefault();
                var target = ev.target;
                var groupid = $(target).attr('data-groupid');
                $('#pintuan_iframe_content iframe').attr("src","http://www.52shangou.com/buyer/pintuan/group-detail.html?groupId="+groupid);
                $('#pintuan_iframe').modal("show");
            });
        }
    };

    /**
     * 渲染订单列表主信息
     * @param data
     */
    function renderOrderListMain(data) {
        if(data){
            data.remarkUrl = CRM.getOuterUrl('/buyer/crm/php/o2o/seller/admin/order_remark.php');
            var html = listTpl({data : data});
            return html;
        }

    }

    window.doSearch = List.searchList;
    return List;
});